<template>
  <div class="search">
    <el-autocomplete
      class="inline-input search-input"
      v-model="wd"
      :fetch-suggestions="querySearch"
      placeholder="请输入搜索内容"
      :trigger-on-focus="false"
      @select="handleSelect"
      :select-when-unmatched="true"
    ></el-autocomplete>
    <el-button
      class="search-button"
      @click="handleClick"
      type="primary"
      icon="el-icon-search"
      :circle="true"
    ></el-button>
  </div>
</template>

<script>
let isMobile = false
const sUserAgent = navigator.userAgent.toLowerCase()
const bIsIpad = sUserAgent.match(/ipad/i) === 'ipad'
const bIsIphoneOs = sUserAgent.match(/iphone os/i) === 'iphone os'
const bIsMidp = sUserAgent.match(/midp/i) === 'midp'
const bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) === 'rv:1.2.3.4'
const bIsUc = sUserAgent.match(/ucweb/i) === 'ucweb'
const bIsAndroid = sUserAgent.match(/android/i) === 'android'
const bIsCE = sUserAgent.match(/windows ce/i) === 'windows ce'
const bIsWM = sUserAgent.match(/windows mobile/i) === 'windows mobile'
if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
  isMobile = true
} else {
  isMobile = false
}

let v = {} // 声明组件对象
window.baidu = { // 当jsonp请求完成后，会调用window.baidu的方法来操作数据
  sug: function (json) {
    v.$data.metaSuggestions = json.s // 将联想词设到data字符串上
  }
}
export default {
  name: 'InputWithImagine',
  data () {
    return {
      choose: '',
      metaSuggestions: [],
      wd: '',
      suggestions: [] // 联想词
    }
  },
  watch: {
    wd () { // 当问题发生变化时调用接口查询联想词
      this.$jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su', {
        wd: this.wd,
        json: 1
      })
      sessionStorage.setItem('history', this.wd)
    }
  },
  methods: {
    handleClick () {
      if (isMobile) {
        window.location.href = 'https://m.baidu.com/s?word=' + this.choose
      } else {
        window.location.href = 'https://www.baidu.com/s?wd=' + this.choose
      }
    },
    handleSelect (item) {
      this.choose = item.value
      this.handleClick()
    },
    querySearch (wd, cb) {
      this.suggestions = []
      // 调用 callback 返回建议列表的数据，所有的显示的值需要包装在value属性中
      this.metaSuggestions.forEach(element => {
        this.suggestions.push({ value: element })
      })
      cb(this.suggestions)
    }
  },
  mounted () {
    v = this // 挂载时导出组件对象
    if (sessionStorage.getItem('history')) {
      this.wd = sessionStorage.getItem('history')
    }
  }
}
</script>

<style lang='stylus' scoped>
.search
  text-align center
  .search-input
    display inline-block
    width 60%
    height 58px
    margin-right 10px
</style>
